/*
 * 文件名：ZkClient.java
 * 描述： ZkClient.java
 * 修改人：Lo&Wang
 * 修改时间：2016年10月10日
 * 修改内容：新增
 */
package com.lowang.zookeeper;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

/**
 * @author zhengmo
 */
public class DistributedZkClient {
    private static final int SESSION_TIMEOUT = 5000;
    public static ZooKeeper build(String connectString) throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);
        ZooKeeper zk = new ZooKeeper(connectString, SESSION_TIMEOUT, new Watcher() {
            public void process(WatchedEvent event) {
                if (event.getState() == KeeperState.SyncConnected) {
                    latch.countDown();
                    System.out.println("连接已经建立");
                }
                if (event.getType() == EventType.NodeDeleted) {
                    System.out.println("节点被删除:" + event.getPath());
                }
            }
        });
        latch.await();
        return zk;
    }
}
